#pragma once

#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <fcntl.h>
#include <unistd.h>

#define FIFO_FILE = "my_fifo"

class Fifo
{
private:
    std::string _path;
    std::string _name;
    std::string _fifoName;

public:
    Fifo(const std::string &path, const std::string &name)
        : _path(path),
          _name(name)
    {
        _fifoName = _path + "/" + _name;
        // 新建管道文件
        int n = mkfifo(_fifoName.c_str(), 0666);
        if (n == -1)
        {
            std::cerr << "命名管道文件创建失败" << std::endl;
        }
        std::cerr << "命名管道文件创建成功" << std::endl;
    }

    ~Fifo()
    {
        // 关闭管道文件
        int closeCode = unlink(_fifoName.c_str());
        if (closeCode == 0)
        {
            std::cout << "管道文件删除成功" << std::endl;
        }
        else
        {
            std::cout << "管道文件删除失败" << std::endl;
        }
    }
};

class FifoOper
{
private:
    std::string _path;
    std::string _name;
    std::string _fifoName;
    int _fd;

public:
    FifoOper(const std::string &path, const std::string &name)
        : _path(path),
          _name(name),
          _fd(-1)
    {
        _fifoName = _path + "/" + _name;
    }

    void OpenWithRead()
    {
        _fd = open(_fifoName.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            std::cerr << "打开命名管道文件失败" << std::endl;
        }
        std::cerr << "打开命名管道文件成功" << std::endl;
    }
    void OpenWithWrite()
    {
        _fd = open(_fifoName.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            std::cerr << "打开命名管道文件失败" << std::endl;
        }
        std::cerr << "打开命名管道文件成功" << std::endl;
    }
    bool Read()
    {
        char c = 0; 
        int n = read(_fd,&c,sizeof(c));
        return n > 0;
    }
    void Write()
    {
        // 写入文件内容
        char c = 'z';
        write(_fd,&c,sizeof(c));
    }
    void Close()
    {
        if(_fd>0)
            close(_fd);
    }

    ~FifoOper() {}
};